<template>
  <div>
    <div>
      <el-input v-model="input" style="width: 400px"></el-input>
      <el-button @click="encrypt">加密</el-button>
      <p>{{ jiami }}</p>
    </div>
    <div>
      <el-input v-model="input1" style="width: 490px"></el-input>
      <el-button @click="decrypt">解密</el-button>
      <p>{{ jiemi }}</p>
    </div>
  </div>
</template>

<script>
import forge from "node-forge";
const keyStr = "12cf3a619cbb468c";
export default {
  name: "test",
  data() {
    return {
      input: "fIOSS#7777",
      input1: "AAAADI+2yibfcdu3AxDM4KM90ITOhhZgtbJQLCkmsuJmXoq26AyqHJ2H",
      jiemi: "请解密",
      jiami: "请加密",
    };
    // 'xW90gVSEygriEeH4U5wIQTOsAk6UpV1T4LhSndZC1zAhSKAE3Rc='
    //AAAADI+2yibfcdu3AxDM4KM90ITOhhZgtbJQLCkmsuJmXoq26AyqHJ2H  //带[0,0,0,12]
  },
  methods: {
    // 加密
    encrypt(word) {
      word = this.input;
      console.log(forge);
      var _iv = this.ab2str(new Uint8Array([0, 0, 0, 12]));
      var iv = forge.random.getBytesSync(12); // 生成随机iv 12字节
      var cipher = forge.cipher.createCipher("AES-GCM", keyStr); // 生成AES-GCM模式的cipher对象 并传入密钥
      cipher.start({
        iv: iv,
      });
      cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(word)));
      cipher.finish();
      var encrypted = cipher.output;
      var tag = cipher.mode.tag;
      let str = window.btoa( _iv +iv + encrypted.data + tag.data);
      this.jiami = str;
      this.input1 = str;
      return str;
    },
    //解密
    decrypt(datamsg) {
      datamsg = this.input1;
      datamsg = atob(datamsg);
      const _iv=datamsg.slice(0, 4);
      const iv = datamsg.slice(4, 16);
      const tag = datamsg.slice(-16);
      const data = datamsg.slice(16, datamsg.length - 16);
      var decipher = forge.cipher.createDecipher("AES-GCM", keyStr);
      decipher.start({
        iv: iv,
        tag: tag,
      });
      decipher.update(forge.util.createBuffer(data));
      console.log(decipher);
      const pass = decipher.finish();
      if (pass) {
        console.log("解密成功");
        this.jiemi = decipher.output.toString();
        return decipher.output.toString();
      } else {
        console.log("解密失败");
      }
    },
    ab2str(buf) {
      // ArrayBuffer 转为字符串
      return String.fromCharCode.apply(null, new Uint8Array(buf));
    },
    str2ab(str) {
      // 字符串转为ArrayBuffer对象，参数为字符串
      var buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
      var bufView = new Uint8Array(buf);
      for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
      }
      return buf;
    },
  },
  mounted() {
   
  },
};
</script>
<style>
</style>
